package com.ruoyi.system.api.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.api.ResponseWithData;
import com.ruoyi.system.api.domain.*;
import com.ruoyi.system.api.mapper.*;
import com.ruoyi.system.api.service.CcService;
import com.ruoyi.system.api.service.IServiceInstrumentService;
import com.ruoyi.system.api.service.IServiceNoticeService;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.api.service.IStInstallationQualityReportService;
import com.ruoyi.common.core.text.Convert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;

/**
 * 安装质量报告 安装质量报告Service业务层处理
 *
 * @author ruoyi
 * @date 2020-03-09
 */
@Service
public class StInstallationQualityReportServiceImpl implements IStInstallationQualityReportService {
    private static final Logger log = LoggerFactory.getLogger(StInstallationQualityReportServiceImpl.class);

    @Autowired
    private StInstallationQualityReportMapper stInstallationQualityReportMapper;
    @Autowired
    private ServiceLogMapper serviceLogMapper;
    @Autowired
    private ReportInfoMapper reportInfoMapper;
    @Autowired
    private StServiceReportMapper stServiceReportMapper;
    @Autowired
    private StMajorPartMapper majorPartMapper;

    @Autowired
    private StEquipmentAccessoryMapper equipmentAccessoryMapper;
    @Autowired
    private StAcceptanceReportMapper stAcceptanceReportMapper;
    /**
     * 调用CC接口service
     */
    @Autowired
    private CcService ccService;

    @Autowired
    private IServiceInstrumentService serviceInstrumentService;

    @Autowired
    private StPhoneReportMapper phoneReportMapper;

    @Autowired
    private StServiceReportMapper serviceReportMapper;

    @Autowired
    private ServiceNoticeMapper serviceNoticeMapper;
    @Autowired
    private StReportPortMapper reportPortMapper;

    @Autowired
    private StReportPortMapper stReportPortMapper;


    /**
     * 查询安装质量报告 安装质量报告
     *
     * @param id 安装质量报告 安装质量报告ID
     * @return 安装质量报告 安装质量报告
     */
    @Override
    public StInstallationQualityReport selectStInstallationQualityReportById(Long id) {
        return stInstallationQualityReportMapper.selectStInstallationQualityReportById(id);
    }

    /**
     * 查询安装质量报告 安装质量报告列表
     *
     * @param stInstallationQualityReport 安装质量报告 安装质量报告
     * @return 安装质量报告 安装质量报告
     */
    @Override
    public List<StInstallationQualityReport> selectStInstallationQualityReportList(StInstallationQualityReport stInstallationQualityReport) {
        return stInstallationQualityReportMapper.selectStInstallationQualityReportList(stInstallationQualityReport);
    }

    /**
     * 新增安装质量报告 安装质量报告
     *
     * @param stInstallationQualityReport 安装质量报告 安装质量报告
     * @return 结果
     */
    @Override
    public int insertStInstallationQualityReport(StInstallationQualityReport stInstallationQualityReport) {
        stInstallationQualityReport.setCreateTime(DateUtils.getNowDate());
        return stInstallationQualityReportMapper.insertStInstallationQualityReport(stInstallationQualityReport);
    }

    /**
     * 修改安装质量报告 安装质量报告
     *
     * @param stInstallationQualityReport 安装质量报告 安装质量报告
     * @return 结果
     */
    @Override
    public int updateStInstallationQualityReport(StInstallationQualityReport stInstallationQualityReport) {
        stInstallationQualityReport.setUpdateTime(DateUtils.getNowDate());
        return stInstallationQualityReportMapper.updateStInstallationQualityReport(stInstallationQualityReport);
    }

    /**
     * 删除安装质量报告 安装质量报告对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteStInstallationQualityReportByIds(String ids) {
        return stInstallationQualityReportMapper.deleteStInstallationQualityReportByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除安装质量报告 安装质量报告信息
     *
     * @param id 安装质量报告 安装质量报告ID
     * @return 结果
     */
    @Override
    public int deleteStInstallationQualityReportById(Long id) {
        return stInstallationQualityReportMapper.deleteStInstallationQualityReportById(id);
    }

    /**
     * 添加安装质量报告
     *
     * @param installationQualityReport
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/9 4:06 下午
     */
    @Override
    public ResponseWithData<?> addInstallationQualityReport(StInstallationQualityReport installationQualityReport) {
        if (installationQualityReport.getPlanId() == null) {
            return new ResponseWithData<>().error("planId cannot be empty！");
        }
        if (installationQualityReport.getNoticeId() == null) {
            return new ResponseWithData<>().error("noticeId cannot be empty！");
        }
        if (installationQualityReport.getEnginnerId() == null) {
            return new ResponseWithData<>().error("enginnerId cannot be empty！");
        }
        if (StringUtils.isEmpty(installationQualityReport.getServiceNo())) {
            return new ResponseWithData<>().error("serviceNo cannot be empty！");
        }
        if (null == installationQualityReport.getInstallStartTime()) {
            return new ResponseWithData<>().error("installStartTime cannot be empty！");
        }
        if (null == installationQualityReport.getInstallEndTime()) {
            return new ResponseWithData<>().error("installEndTime cannot be empty！");
        }
//        if (null == installationQualityReport.getWarrantyStartTime()) {
//            return new ResponseWithData<>().error("warrantyStartTime cannot be empty！");
//        }
//        if (null == installationQualityReport.getWarrantyEndTime()) {
//            return new ResponseWithData<>().error("warrantyEndTime cannot be empty！");
//        }
        if (null == installationQualityReport.getWorkTime()) {
            return new ResponseWithData<>().error("workTime cannot be empty！");
        }
        if (null == installationQualityReport.getTripTime()) {
            return new ResponseWithData<>().error("tripTime cannot be empty！");
        }

        // 1、保存安装质量报告信息
        installationQualityReport.setCreateTime(new Date());
        installationQualityReport.setCreateBy(installationQualityReport.getEnginnerId() + "");
        installationQualityReport.setDelFlag("0");
        installationQualityReport.setSyncFlag("0");
        stInstallationQualityReportMapper.insertStInstallationQualityReport(installationQualityReport);

        // 2、更新主要设备信息
//        majorPartMapper.updateStMajorPartByHelpIdAndServiceNo(installationQualityReport.getId(), installationQualityReport.getServiceNo(), installationQualityReport.getHelpId());

        // 3、更新附属设备信息
//        equipmentAccessoryMapper.updateStEquipmentAccessoryByHelpIdAndServiceNo(installationQualityReport.getId(), installationQualityReport.getServiceNo(), installationQualityReport.getHelpId());

        // 4、安装质量报告保存到主表 st_report_info
        ReportInfo reportInfo = new ReportInfo();
        reportInfo.setServiceNo(installationQualityReport.getServiceNo());
        reportInfo.setEnginnerId(installationQualityReport.getEnginnerId());
        reportInfo.setPlanId(installationQualityReport.getPlanId());
        reportInfo.setRelServiceNo(5L);
        reportInfo.setRelPlanId("st_installation_quality_report");
        reportInfo.setBatchType(installationQualityReport.getId());
        reportInfo.setDelFlag("0");
        reportInfo.setCreateTime(new Date());
        reportInfo.setCreateBy(installationQualityReport.getEnginnerId() + "");
        reportInfo.setNoticeId(installationQualityReport.getNoticeId());
        reportInfo.setSyncFlag("0");
        reportInfo.setFseName(installationQualityReport.getFseName());
        // TODO 报告编号生成规则是什么
        reportInfoMapper.insertStReportInfo(reportInfo);
        //
        // /跟新备件状态
//

        return new ResponseWithData<>().success(installationQualityReport).code(200);
    }

    /**
     * 添加安装质量报告
     *
     * @param installationQualityReport
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/9 4:06 下午
     */
    @Override
    public ResponseWithData<?> addInstallationQualityReport2(StInstallationQualityReport installationQualityReport) {
        if (installationQualityReport.getPlanId() == null) {
            return new ResponseWithData<>().error("planId cannot be empty！");
        }
        if (installationQualityReport.getNoticeId() == null) {
            return new ResponseWithData<>().error("noticeId cannot be empty！");
        }
        if (installationQualityReport.getEnginnerId() == null) {
            return new ResponseWithData<>().error("enginnerId cannot be empty！");
        }
        if (StringUtils.isEmpty(installationQualityReport.getServiceNo())) {
            return new ResponseWithData<>().error("serviceNo cannot be empty！");
        }
        if (null == installationQualityReport.getInstallStartTime()) {
            return new ResponseWithData<>().error("installStartTime cannot be empty！");
        }
        if (null == installationQualityReport.getInstallEndTime()) {
            return new ResponseWithData<>().error("installEndTime cannot be empty！");
        }
//        if (null == installationQualityReport.getWarrantyStartTime()) {
//            return new ResponseWithData<>().error("warrantyStartTime cannot be empty！");
//        }
//        if (null == installationQualityReport.getWarrantyEndTime()) {
//            return new ResponseWithData<>().error("warrantyEndTime cannot be empty！");
//        }
        if (null == installationQualityReport.getWorkTime()) {
            return new ResponseWithData<>().error("workTime cannot be empty！");
        }
        if (null == installationQualityReport.getTripTime()) {
            return new ResponseWithData<>().error("tripTime cannot be empty！");
        }

        // 1、保存安装质量报告信息--软件
        installationQualityReport.setCreateTime(new Date());
        installationQualityReport.setCreateBy(installationQualityReport.getEnginnerId() + "");
        installationQualityReport.setDelFlag("0");
        installationQualityReport.setSyncFlag("0");
        stInstallationQualityReportMapper.insertStInstallationQualityReport(installationQualityReport);

        // 2、更新主要设备信息
        majorPartMapper.updateStMajorPartByHelpIdAndServiceNo(installationQualityReport.getId(), installationQualityReport.getServiceNo(), installationQualityReport.getHelpId());

        // 3、更新附属设备信息
//        equipmentAccessoryMapper.updateStEquipmentAccessoryByHelpIdAndServiceNo(installationQualityReport.getId(), installationQualityReport.getServiceNo(), installationQualityReport.getHelpId());

        // 4、安装质量报告保存到主表 st_report_info
        ReportInfo reportInfo = new ReportInfo();
        reportInfo.setServiceNo(installationQualityReport.getServiceNo());
        reportInfo.setEnginnerId(installationQualityReport.getEnginnerId());
        reportInfo.setPlanId(installationQualityReport.getPlanId());
        reportInfo.setRelServiceNo(5L);
        reportInfo.setRelPlanId("st_installation_quality_report");
        reportInfo.setBatchType(installationQualityReport.getId());
        reportInfo.setDelFlag("0");
        reportInfo.setCreateTime(new Date());
        reportInfo.setCreateBy(installationQualityReport.getEnginnerId() + "");
        reportInfo.setNoticeId(installationQualityReport.getNoticeId());
        reportInfo.setSyncFlag("0");
        reportInfo.setFseName(installationQualityReport.getFseName());
        // TODO 报告编号生成规则是什么
        reportInfoMapper.insertStReportInfo(reportInfo);
        //
        // /跟新备件状态

        String[] delPartIds = installationQualityReport.getSaveDelPartIds().split(",");
        HashMap partkeys = new HashMap();
        for (int i = 0; i < delPartIds.length; i++) {
            partkeys.put(delPartIds[i], delPartIds[i]);
        }

        StReportPort searchStReportPort = new StReportPort();
        searchStReportPort.setServiceNo(installationQualityReport.getServiceNo());
        searchStReportPort.setPortType("5");
        searchStReportPort.setDelFlag("0");
        searchStReportPort.setSsflag("0");
        List<StReportPort> stReportPortList = stReportPortMapper.selectStReportPortList(searchStReportPort);
        for (StReportPort stReportPort : stReportPortList) {
            if (!partkeys.containsKey(stReportPort.getId())) {
                stReportPort.setSsflag("1");
                stReportPortMapper.updateStReportPort(stReportPort);
            } else {
                stReportPort.setDelFlag("2");
                stReportPortMapper.updateStReportPort(stReportPort);
            }
        }

        return new ResponseWithData<>().success(installationQualityReport).code(200);
    }


    /**
     * 修改安装质量报告
     *
     * @param installationQualityReport
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/9 4:06 下午
     */
    @Override
    public ResponseWithData<?> updateInstallationQualityReport(StInstallationQualityReport installationQualityReport) {
        if (installationQualityReport.getId() == null) {
            return new ResponseWithData<>().error("id cannot be empty！");
        }
        if (installationQualityReport.getPlanId() == null) {
            return new ResponseWithData<>().error("planId cannot be empty！");
        }
        if (installationQualityReport.getNoticeId() == null) {
            return new ResponseWithData<>().error("noticeId cannot be empty！");
        }
        if (installationQualityReport.getEnginnerId() == null) {
            return new ResponseWithData<>().error("enginnerId cannot be empty！");
        }
        if (StringUtils.isEmpty(installationQualityReport.getServiceNo())) {
            return new ResponseWithData<>().error("serviceNo cannot be empty！");
        }
        if (null == installationQualityReport.getInstallStartTime()) {
            return new ResponseWithData<>().error("installStartTime cannot be empty！");
        }
        if (null == installationQualityReport.getInstallEndTime()) {
            return new ResponseWithData<>().error("installEndTime cannot be empty！");
        }
//        if (null == installationQualityReport.getWarrantyStartTime()) {
//            return new ResponseWithData<>().error("warrantyStartTime cannot be empty！");
//        }
//        if (null == installationQualityReport.getWarrantyEndTime()) {
//            return new ResponseWithData<>().error("warrantyEndTime cannot be empty！");
//        }
        if (null == installationQualityReport.getWorkTime()) {
            return new ResponseWithData<>().error("workTime cannot be empty！");
        }
        if (null == installationQualityReport.getTripTime()) {
            return new ResponseWithData<>().error("tripTime cannot be empty！");
        }

        // 1、保存安装质量报告信息
        installationQualityReport.setUpdateTime(new Date());
        installationQualityReport.setUpdateBy(installationQualityReport.getEnginnerId() + "");
        stInstallationQualityReportMapper.updateStInstallationQualityReport(installationQualityReport);

        ReportInfo reportInfo = reportInfoMapper.selectStReportInfoByBatchType(installationQualityReport.getId(), "5");
        reportInfo.setUpdateBy(installationQualityReport.getEnginnerId() + "");
        reportInfo.setUpdateTime(new Date());
        // reportInfo.setEnginnerId(installationQualityReport.getEnginnerId());
        //reportInfo.setFseName(installationQualityReport.getFseName());
        reportInfoMapper.updateStReportInfo(reportInfo);

        // 2、更新主要设备信息
//        majorPartMapper.updateStMajorPartByHelpIdAndServiceNo(installationQualityReport.getId(), installationQualityReport.getServiceNo(), installationQualityReport.getHelpId());

        // 3、更新附属设备信息
//        equipmentAccessoryMapper.updateStEquipmentAccessoryByHelpIdAndServiceNo(installationQualityReport.getId(), installationQualityReport.getServiceNo(), installationQualityReport.getHelpId());
//更新备件状态

        // /跟新备件状态
        String[] delPartIds = installationQualityReport.getSaveDelPartIds().split(",");
        HashMap partkeys = new HashMap();
        for (int i = 0; i < delPartIds.length; i++) {
            partkeys.put(delPartIds[i], delPartIds[i]);
        }

        StReportPort searchStReportPort = new StReportPort();
        searchStReportPort.setServiceNo(installationQualityReport.getServiceNo());
        searchStReportPort.setPortType("5");
        searchStReportPort.setDelFlag("0");
        searchStReportPort.setSsflag("0");
        List<StReportPort> stReportPortList = stReportPortMapper.selectStReportPortList(searchStReportPort);
        for (StReportPort stReportPort : stReportPortList) {
            if (!partkeys.containsKey(stReportPort.getId())) {
                stReportPort.setSsflag("1");
                stReportPortMapper.updateStReportPort(stReportPort);
            } else {
                stReportPort.setDelFlag("2");
                stReportPortMapper.updateStReportPort(stReportPort);
            }
        }

        return new ResponseWithData<>().success(installationQualityReport).code(200);
    }

    public static List<StReportPort> removeDupliById(List<StReportPort> persons) {
        Set<StReportPort> personSet = new TreeSet<>((o1, o2) -> o1.getPid().compareTo(o2.getPid()));
        personSet.addAll(persons);
        return new ArrayList<>(personSet);
    }

    /**
     * 提交安装质量报告
     *
     * @param id         安装质量报告主键ID
     * @param enginnerId 提交的工程师ID
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/9 4:07 下午
     */
    @Override
    public ResponseWithData<?> installationQualityReportSubmit(Long id, Long enginnerId) {

        if (null == id) {
            return new ResponseWithData<>().error().msg("id cannot be empty");
        }
        if (null == enginnerId) {
            return new ResponseWithData<>().error().msg("enginnerId cannot be empty");
        }
        // 查寻安装质量报告基本信息
        StInstallationQualityReport stInstallationQualityReport = stInstallationQualityReportMapper.selectStInstallationQualityReportById(id);
        ReportInfo reportInfo = reportInfoMapper.selectStReportInfoByBatchType(id, "5");

        if (!(enginnerId + "").equals(reportInfo.getEnginnerId() + "")) {
            String name = reportInfo.getFseName();
            return new ResponseWithData<>().error().msg("你不能提交" + name + "的报告, 如需提交请联系" + name);
        }

        if (null == stInstallationQualityReport || null == reportInfo) {
            return new ResponseWithData<>().error().msg("安装质量报告不存在");
        }
        if ("1".equals(reportInfo.getSyncFlag())) {
            return new ResponseWithData<>().error().msg("此安装质量报告已提交过");
        }

        Map<String, Object> params = new HashMap<>();
        // 唯一主键
        params.put("report_guid", reportInfo.getId().toString());
        // Service号
        params.put("service_no", reportInfo.getServiceNo());
        // 提交的工程师ID
        params.put("enginner_id", enginnerId + "");
        // 安装开始
        params.put("install_start_time", DateUtils.parseDateToStrEmpty(DateUtils.YYYY_MM_DD_HH_MM_SS, stInstallationQualityReport.getInstallStartTime()));
        // 安装结束
        params.put("install_end_time", DateUtils.parseDateToStrEmpty(DateUtils.YYYY_MM_DD_HH_MM_SS, stInstallationQualityReport.getInstallEndTime()));
        // 保修开始
        params.put("warranty_start_time", DateUtils.parseDateToStrEmpty(DateUtils.YYYY_MM_DD_HH_MM_SS, stInstallationQualityReport.getWarrantyStartTime()));
        // 保修结束
        params.put("warranty_end_time", DateUtils.parseDateToStrEmpty(DateUtils.YYYY_MM_DD_HH_MM_SS, stInstallationQualityReport.getWarrantyEndTime()));
        // 工作小时
        params.put("work_time", stInstallationQualityReport.getWorkTime() + "");
        // 旅途小时
        params.put("trip_time", stInstallationQualityReport.getTripTime() + "");
        // 浪费小时
        params.put("Waste_time", stInstallationQualityReport.getWasteTime() + "");
        // 加班小时
        params.put("overwork_time", stInstallationQualityReport.getWorkOvertime() + "");
        // 电脑厂家
        params.put("ComputerMfr", stInstallationQualityReport.getComputerMfr());
        // 服务号
        params.put("ServiceNo", stInstallationQualityReport.getServiceNumber());
        // 电脑型号
        params.put("CompModel", stInstallationQualityReport.getModelNumber());
        // 系统软件
        params.put("SysSoft", stInstallationQualityReport.getSystemSoftware());
        // 操作系统（操作软件）
        params.put("Software", stInstallationQualityReport.getSoftware());
        // 选项软件
        params.put("OptionSoft", stInstallationQualityReport.getOptionSoftware());
        // 设备类型1
        params.put("EquType1", stInstallationQualityReport.getEquipmentType1());
        // 序列号1
        params.put("Serial1", stInstallationQualityReport.getSerialNumber1());
        // 设备类型2
        params.put("EquType2", stInstallationQualityReport.getEquipmentType2());
        // 序列号2
        params.put("Serial2", stInstallationQualityReport.getSerialNumber2());
        // 设备类型3
        params.put("EquType3", stInstallationQualityReport.getEquipmentType3());
        // 序列号3
        params.put("Serial3", stInstallationQualityReport.getSerialNumber3());

        // 仪器设备附属信息
        List<StEquipmentAccessory> equipmentAccessories = equipmentAccessoryMapper.selectStEquipmentAccessoryListByInstallationQualityReportId(stInstallationQualityReport.getId());
        if (null != equipmentAccessories) {
            List<Map<String, Object>> equipmentAccessorieParams = new ArrayList<>();
            for (StEquipmentAccessory equipmentAccessory : equipmentAccessories) {
                Map<String, Object> equipmentAccessorieParam = new HashMap<>();
                // 附件名称
                equipmentAccessorieParam.put("accessory_name", equipmentAccessory.getAccessoryName());
                // 附件序列号
                equipmentAccessorieParam.put("serial_number", equipmentAccessory.getSerialNumber());
                // 保修开始时间
                equipmentAccessorieParam.put("warranty_start_time", equipmentAccessory.getWarrantyStartTime());
                // 保修结束时间
                equipmentAccessorieParam.put("warranty_end_time", equipmentAccessory.getWarrantyEndTime());
                // 备注
                equipmentAccessorieParam.put("remark", StringUtils.isEmpty(equipmentAccessory.getRemark()) ? "" : equipmentAccessory.getRemark());

                equipmentAccessorieParams.add(equipmentAccessorieParam);
            }
            params.put("equipment_accessory_data", equipmentAccessorieParams);
        } else {
            params.put("equipment_accessory_data", new ArrayList<>());
        }

        //   主要设备信息
        List<StMajorPart> stMajorParts = majorPartMapper.selectStMajorPartListByInstallationQualityReportId(stInstallationQualityReport.getId());
        if (null != stMajorParts) {
            List<Map<String, Object>> majorPartParams = new ArrayList<>();
            for (StMajorPart stMajorPart : stMajorParts) {
                Map<String, Object> majorPartParam = new HashMap<>();
                // 备件号
                majorPartParam.put("part_number", stMajorPart.getPartNumber());
                // 备件名称
                majorPartParam.put("part_name", stMajorPart.getPartName());
                // 序列号
                majorPartParam.put("serial_number", stMajorPart.getSerialNumber());
                // 保修开始时间
                majorPartParam.put("warranty_start_time", stMajorPart.getWarrantyStartTime());
                // 保修结束时间
                majorPartParam.put("warranty_end_time", stMajorPart.getWarrantyEndTime());
                // 备注
                majorPartParam.put("remark", StringUtils.isEmpty(stMajorPart.getRemark()) ? "" : stMajorPart.getRemark());

                majorPartParams.add(majorPartParam);
            }
            params.put("major_part_data", majorPartParams);
        } else {
            params.put("major_part_data", new ArrayList<>());
        }
        //获取已提交的报告备件
        //  List<StReportPort> reportPorts = reportPortMapper.getSubmitServiceAndPhoneReportPorts(stInstallationQualityReport.getServiceNo());

        //   List<StReportPort> reportPorts = reportPortMapper.getSubmitServiceAndPhoneReportPorts(stInstallationQualityReport.getServiceNo());

        StReportPort searchStReportPort = new StReportPort();
        searchStReportPort.setServiceNo(stInstallationQualityReport.getServiceNo());
        searchStReportPort.setPortType("5");
        searchStReportPort.setDelFlag("0");
        searchStReportPort.setSsflag("1");
        List<StReportPort> reportPorts = stReportPortMapper.selectStReportPortList(searchStReportPort);

        if (reportPorts.size() > 0) {
            //  reportPorts = removeDupliById(reportPorts);
            List<Map<String, Object>> reportPortParams = new ArrayList<>();
            for (StReportPort reportPort : reportPorts) {
                Map<String, Object> reportPortParam = new HashMap<>();
                // 备件号
                reportPortParam.put("part_number", reportPort.getPartNumber());
                // 借贷单号
                reportPortParam.put("loan_number", reportPort.getLoanNumber());
                // 备件序列号
                if (StringUtils.isEmpty(reportPort.getPartSerialNumber())) {
                    reportPortParam.put("part_serial_number", "");
                } else {
                    reportPortParam.put("part_serial_number", reportPort.getPartSerialNumber());
                }

                // 备件名称
                reportPortParam.put("part_name", reportPort.getPartName());
                // QTY数量  备件数量
                reportPortParam.put("qty_count", reportPort.getQtyCount());
                // Price单价
                reportPortParam.put("price", reportPort.getPrice());
                // Price总价
                reportPortParam.put("totalprice", reportPort.getTotalprice());
                // 更换类型 备件类型
                reportPortParam.put("part_type", StringUtils.isEmpty(reportPort.getPartType()) ? "" : reportPort.getPartType());
                // 备注
                reportPortParam.put("remark", StringUtils.isEmpty(reportPort.getRemark()) ? "" : reportPort.getRemark());
                // 备件收货地址
                reportPortParam.put("Address", StringUtils.isEmpty(reportPort.getAddress()) ? "" : reportPort.getAddress());
                reportPortParams.add(reportPortParam);
            }
            params.put("part_data", JSON.toJSONString(reportPortParams));
        } else {
            params.put("part_data", new ArrayList<>());
        }
        // 请求CC接口 提交电话解决报告
        String response = ccService.installqualityReporthandle(params);
        // 更新备件 已提交的内容
        for (StReportPort stReportPort : reportPorts) {
            stReportPort.setSsflag("2");
            stReportPortMapper.updateStReportPort(stReportPort);
        }

        /** 如果调用接口异常直接返回 */
        if (null == response) {
            return new ResponseWithData().error().msg("提交安装质量报告失败 调用CC端提交安装质量报告接口发生异常").code(202);
        }

        JSONObject jsonObject = JSONObject.parseObject(response);
        String status = jsonObject.getString("status");
        if ("1".equals(status)) {
            String rptNo = "";
            try {
                JSONArray record = jsonObject.getJSONArray("record");
                if (record != null && record.size() > 0) {
                    rptNo = record.getJSONObject(0).getString("rpt_no");
                }
            } catch (Exception e) {
                log.error("程序异常", e.getMessage());
            }

            // 提交成功 ，更新同步状态
            ReportInfo info = new ReportInfo();
            info.setId(reportInfo.getId());
            info.setSyncFlag("1");
            info.setSyncTime(new Date());
            info.setReportNo(rptNo);
            reportInfoMapper.updateStReportInfo(info);

            return new ResponseWithData().success().msg("提交安装质量报告成功").code(200);
        } else if ("2".equals(status)) {
            String message = jsonObject.getString("message");
            return new ResponseWithData().error().msg(message).code(201);
        } else {
            return new ResponseWithData().error().msg("提交安装质量报告失败 调用CC端提交安装质量报告接口发生异常").code(201);
        }
    }

    /**
     * 查看安装质量报告
     *
     * @param id
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/9 4:08 下午
     */
    @Override
    public ResponseWithData<?> detailInstallationQualityReport(Long id) {
        ReportInfo reportInfo = reportInfoMapper.selectStReportInfoById(id);
        if (null != reportInfo) {
            StInstallationQualityReport stInstallationQualityReport = stInstallationQualityReportMapper.selectStInstallationQualityReportById(id);
            reportInfo.setReportInfo(stInstallationQualityReport);
        }
        return new ResponseWithData<>().success(reportInfo).code(200);
    }

    private String getStartWorkingTime(List<ServiceLog> serviceLogs) {
        ServiceLog minStartTime = Collections.min(serviceLogs, new Comparator<ServiceLog>() {
            @Override
            public int compare(ServiceLog o1, ServiceLog o2) {
                int flag = 0;
                try {
                    if (null != o1.getStartTime() && null != o2.getStartTime()) {
                        if (o1.getStartTime().getTime() > o2.getStartTime().getTime()) {
                            flag = 1;
                        } else if (o1.getStartTime().getTime() < o2.getStartTime().getTime()) {
                            flag = -1;
                        } else {
                            flag = 0;
                        }
                    } else {
                        if (null == o2.getStartTime() && null != o1.getStartTime()) {
                            flag = -1;
                        } else if (null == o1.getStartTime() && null != o2.getStartTime()) {
                            flag = 1;
                        } else {
                            flag = 0;
                        }
                    }
                } catch (Exception e) {
                    log.error("程序异常", e.getMessage());
                }
                return flag;
            }
        });
        if (null != minStartTime) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return sdf.format(minStartTime.getStartTime());
        }
        return "";
    }

    private String getEndWorkingTime(List<ServiceLog> serviceLogs) {
        ServiceLog maxEndTime = Collections.max(serviceLogs, new Comparator<ServiceLog>() {
            @Override
            public int compare(ServiceLog o1, ServiceLog o2) {
                int flag = 0;
                try {
                    if (null != o1.getEndTime() && null != o2.getEndTime()) {
                        if (o1.getEndTime().getTime() > o2.getEndTime().getTime()) {
                            flag = 1;
                        } else if (o1.getEndTime().getTime() < o2.getEndTime().getTime()) {
                            flag = -1;
                        } else {
                            flag = 0;
                        }
                    } else {
                        if (null == o2.getEndTime() && null != o1.getEndTime()) {
                            flag = -1;
                        } else if (null == o1.getEndTime() && null != o2.getEndTime()) {
                            flag = 1;
                        } else {
                            flag = 0;
                        }
                    }
                } catch (Exception e) {
                    log.error("程序异常", e.getMessage());
                }
                return flag;
            }
        });
        if (null != maxEndTime) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return sdf.format(maxEndTime.getEndTime());
        }
        return "";
    }

    @Override
    public ResponseWithData<?> initData(String serviceNo, String enginnerId) {
        ServiceInstrument serviceInstrument = new ServiceInstrument();
        serviceInstrument.setServiceNo(serviceNo);
        List<ServiceInstrument> serviceInstrumentList = serviceInstrumentService.selectServiceInstrumentList(serviceInstrument);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("serviceInstrumentList", serviceInstrumentList);

        String state = "";
        // 如果有报告【服务报告或电话解决报告】，就自动带出最后一次报告里的备件(这个报告已完成未完成都可以）
        List<ReportInfo> reportInfo = reportInfoMapper.getReportInfo(serviceNo, enginnerId);
        if (null != reportInfo && reportInfo.size() > 0) {
            if (1 == reportInfo.get(0).getRelServiceNo() && "1".equals(reportInfo.get(0).getServiceResult())) {
                state = "stServiceReport";
                // 服务报告
                StServiceReport stServiceReport = serviceReportMapper.selectStServiceReportById(reportInfo.get(0).getBatchType());
                jsonObject.put("stServiceReport", stServiceReport);
            } else if (6 == reportInfo.get(0).getRelServiceNo() && "1".equals(reportInfo.get(0).getServiceResult())) {
                state = "stPhoneReport";
                // 电话解决报告
                StPhoneReport stPhoneReport = phoneReportMapper.selectStPhoneReportById(reportInfo.get(0).getBatchType());
                jsonObject.put("stPhoneReport", stPhoneReport);
            }
        }

        jsonObject.put("state", state);

        //安装工程师信息
        //如果有安装验收报告，带出安装验收报告
        List<ReportInfo> reportInfoList = reportInfoMapper.getCheckReport(serviceNo, enginnerId);

        StAcceptanceReport stAcceptanceReport = null;
        if (!ObjectUtils.isEmpty(reportInfoList)) {
            stAcceptanceReport = stAcceptanceReportMapper.selectStAcceptanceReportById(reportInfoList.get(0).getBatchType());
        }
        String startTime = "";
        String endTime = "";
        if (!ObjectUtils.isEmpty(reportInfoList) && !ObjectUtils.isEmpty(stAcceptanceReport)) {
            startTime = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm", stAcceptanceReport.getInstallStartTime());
            endTime = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm", stAcceptanceReport.getInstallEndTime());
        } else {
            Map<String, Object> log = new HashMap();
            log.put("serviceNo", serviceNo);
            List<ServiceLog> serviceLogs = serviceLogMapper.selectTimeLog(log);
            if (!ObjectUtils.isEmpty(serviceLogs)) {
                startTime = getStartWorkingTime(serviceLogs);
                endTime = getEndWorkingTime(serviceLogs);
            }

        }
        JSONObject fse = new JSONObject();
        fse.put("startTime", startTime);
        fse.put("endTime", endTime);
        jsonObject.put("fse", fse);
        //工时信息
        JSONObject workinfo = new JSONObject();
        BigDecimal workTime = new BigDecimal("0.00");
        BigDecimal travelTime = new BigDecimal("0.00");
        List<StServiceReport> serviceReportList = stServiceReportMapper.selectStServiceReportByServiceNo(serviceNo);
        for (StServiceReport stServiceReport : serviceReportList) {
            workTime = workTime.add(new BigDecimal(stServiceReport.getTotalWorkingHours()));
            travelTime = travelTime.add(new BigDecimal(stServiceReport.getTravelTime()));
        }

        workinfo.put("workTime", workTime);

        workinfo.put("travelTime", travelTime);
        jsonObject.put("workinfo", workinfo);

        //获取保修开始时间和保修结束时间
        JSONObject baoxiu = new JSONObject();
        baoxiu.put("startTime", "");
        baoxiu.put("endTime", "");
        if (!ObjectUtils.isEmpty(stAcceptanceReport)) {
            if (!ObjectUtils.isEmpty(stAcceptanceReport.getAcceptanceTime())) {
                baoxiu.put("startTime", DateUtils.parseDateToStr("yyyy-MM-dd HH:mm", stAcceptanceReport.getAcceptanceTime()));
            }
        }

        if (!ObjectUtils.isEmpty(serviceInstrumentList)) {
            if (ObjectUtils.isEmpty(baoxiu.get("startTime"))) {
                if (!ObjectUtils.isEmpty(serviceInstrumentList.get(0).getGuaranteeStartTime())) {
                    baoxiu.put("startTime", DateUtils.parseDateToStr("yyyy-MM-dd HH:mm", serviceInstrumentList.get(0).getGuaranteeStartTime()));
                }
            }
            if (!ObjectUtils.isEmpty(serviceInstrumentList.get(0).getGuaranteeEndTime())) {
                baoxiu.put("endTime", DateUtils.parseDateToStr("yyyy-MM-dd HH:mm", serviceInstrumentList.get(0).getGuaranteeEndTime()));

            }
        }
        jsonObject.put("baoxiu", baoxiu);
        return new ResponseWithData<>().success(jsonObject).msg("查询成功").code(200);

    }

    @Override
    public ResponseWithData<?> initSoftwareAndPartsData(String serviceNo, String instrumentCode) {
        ServiceNotice serviceNotice = new ServiceNotice();
        serviceNotice.setServiceNo(serviceNo);
        List<ServiceNotice> serviceNoticeList = serviceNoticeMapper.selectServiceNoticeList(serviceNotice);
        for (ServiceNotice serviceNoticetemp : serviceNoticeList) {
            JSONObject jsonObject = ccService.getOtherInstrumentHandle(instrumentCode, null);
            JSONArray jsonArray = jsonObject.getJSONArray("record");
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject object = (JSONObject) jsonArray.get(i);
                String equipment_type1 = object.getString("equipment_type1");
                serviceNoticetemp.setEquipment_type1(equipment_type1);
                String serial_number1 = object.getString("serial_number1");
                serviceNoticetemp.setSerial_number1(serial_number1);
                String equipment_type2 = object.getString("equipment_type2");
                serviceNoticetemp.setEquipment_type2(equipment_type2);
                String serial_number2 = object.getString("serial_number2");
                serviceNoticetemp.setSerial_number2(serial_number2);
                String equipment_type3 = object.getString("equipment_type3");
                serviceNoticetemp.setEquipment_type3(equipment_type3);
                String serial_number3 = object.getString("serial_number3");
                serviceNoticetemp.setSerial_number3(serial_number3);
            }


        }

        return new ResponseWithData<>().success(serviceNoticeList).msg("查询成功").code(200);
    }
}
